//
//  JSLHomeController.m
//  JingleSpeedLoan
//
//  Created by 宋质彬 on 2018/6/19.
//  Copyright © 2018年 宋质彬. All rights reserved.
//

#import "JSLHomeController.h"
#import "SDCycleScrollView.h"
#import "CCPScrollView.h"
#import "SYJMoreProductView.h"
#import "JSLProductCell.h"
#import "JSLLoanDetialController.h"
#import "JSLLabelLoanController.h"
#import "H5WebViewController.h"
@interface JSLHomeController ()
<SDCycleScrollViewDelegate,UITableViewDelegate,UITableViewDataSource,SYJMoreProductViewDelegate>
@property (nonatomic , strong) SDCycleScrollView *cycleScrollerView;
@property (nonatomic , strong) CCPScrollView *ccpView;
@property (nonatomic , strong) UITableView *tableView;
@property (nonatomic , strong) UIView *headerView;
@property (nonatomic , strong) SYJMoreProductView *canScrollerView;
@property (nonatomic , strong) UIView *kindBackView;
@property (nonatomic , strong) NSArray *bannerList;
@property (nonatomic , strong) NSArray *noticeList;
@property (nonatomic , strong) NSArray *hotList;
@property (nonatomic , strong) NSArray *allProductList;

@end

@implementation JSLHomeController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"首页";

    [self tableView];
    
    [self.headerView addSubview:self.cycleScrollerView];
    [self.headerView addSubview:self.ccpView];
    [self.headerView addSubview:self.canScrollerView];
    [self.headerView addSubview:self.kindBackView];
    
    self.headerView.height = CGRectGetMaxY(self.kindBackView.frame) +10*AutoSizeScaleYY;
    self.tableView.tableHeaderView = self.headerView;
    
    
    [self configBannerData];
    
    [self congigHotProductData];
    
    [self congigAllProductData];
    
    [self configGongGData];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.navigationController.navigationBar.prefersLargeTitles = NO;
        
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    [HttpRequest judgeNetworkStatusWithSuccess:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusNotReachable) {
            
            [self tipWarnAddContacts];
        }
    }];
}

#pragma mark -
- (void)tipWarnAddContacts {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"网络连接失败，请重新连接网络以取得更好的体验" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"我知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self refreshData];
    }];
    
    [alertVC addAction:sure];
    
    //展示
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)refreshData {
    
    [self configBannerData];
    
    [self congigHotProductData];
    
    [self congigAllProductData];
    
}

- (void)configGongGData {
    
    [HttpRequest POST:LOAN_QUERYNOTICE parameters:nil success:^(id  _Nullable result, NSString * _Nullable successMessage) {
        NSLog(@"%@",result);
        self.noticeList = result[@"data"][@"notice"];
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (NSDictionary *noticeInfo in self.noticeList) {
            
            [array addObject:[NSString stringWithFormat:@"%@用户成功申请%@%@元。",noticeInfo[@"userPhone"],noticeInfo[@"productName"],noticeInfo[@"applyAmount"]]];
          
        }
        
        self.ccpView.titleArray = [NSArray arrayWithArray:array];
        self.ccpView.titleFont = 10;
        self.ccpView.titleColor = [@"#8f8f8f" hexStringToColor];
        
       
        
    } failure:^(NSInteger code, NSString * _Nullable errorMessage) {
        [self.tableView.mj_header endRefreshing];
        [self showMessage:errorMessage];
    }];
}


- (void)configBannerData {
    
    [HttpRequest POST:HOME_BANNER_DATA_URL parameters:nil success:^(id  _Nullable result, NSString * _Nullable successMessage) {
        NSLog(@"%@",result);
        self.bannerList = result[@"data"][@"bannerList"];
        
        NSMutableArray *imageArray = [[NSMutableArray alloc] init];
        for (NSDictionary *info in self.bannerList) {
            [imageArray addObject:info[@"bannerImage"]];
        }
        
        self.cycleScrollerView.imageURLStringsGroup =imageArray;
        
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSInteger code, NSString * _Nullable errorMessage) {
        [self.tableView.mj_header endRefreshing];
        [self showMessage:errorMessage];
    }];
}


- (void)congigHotProductData {
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    parameters[@"publishApp"] = @"2";
    parameters[@"productType"] = @"4";
    parameters[@"productId"] = @"";
    parameters[@"pageNum"] = @"1";
    parameters[@"pageSize"] = @"30";
   
    [HttpRequest POST:HOME_HOT_URL parameters:parameters success:^(id  _Nullable result, NSString * _Nullable successMessage) {
        NSLog(@"%@",result);
        self.hotList = result[@"data"][@"hotProductList"];
        [self.canScrollerView configLoanRecodeMoreProduct:self.hotList];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSInteger code, NSString * _Nullable errorMessage) {
        [self showMessage:errorMessage];
        [self.tableView.mj_header endRefreshing];
    }];
    
}

- (void)congigAllProductData {
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    parameters[@"publishApp"] = @"IOS";
//    parameters[@"productType"] = @"4";
//    parameters[@"productId"] = @"";
    parameters[@"pageNum"] = @"1";
    parameters[@"pageSize"] = @"6";
    
    [HttpRequest POST:HOME_ALL_PRODUCT_URL parameters:parameters success:^(id  _Nullable result, NSString * _Nullable successMessage) {
        NSLog(@"%@",result);
        self.allProductList = result[@"data"][@"productList"];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSInteger code, NSString * _Nullable errorMessage) {
        [self.tableView.mj_header endRefreshing];
        [self showMessage:errorMessage];
    }];
    
}
#pragma mark - SYJMoreProductViewDelegate
- (void)tapMoreProduct:(SYJMoreProductView *)moreProduct info:(NSDictionary *)info {
   
 
        JSLLoanDetialController *loanDetial = [[JSLLoanDetialController alloc] init];
        [loanDetial configLoanDetial:info fromFlag:LoanFromNormal];
        [self pushViewController:loanDetial animated:YES];
    
}

#pragma mark - SDCycleScrollViewDelegate
/** 点击图片回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    
    NSDictionary *bannerinfo = self.bannerList[index];
    
    if ([bannerinfo[@"actionType"] integerValue] ==1) {
      
            JSLLoanDetialController *loanDetial = [[JSLLoanDetialController alloc] init];
            [loanDetial configLoanDetial:self.bannerList[index] fromFlag:LoanFromBanner];
            [self pushViewController:loanDetial animated:YES];
        
    }else {
        
        H5WebViewController *webVC = [[H5WebViewController alloc] init];
        webVC.url = bannerinfo[@"targetUrl"];
        [self pushViewController:webVC animated:YES];
    
    
    }
 
}

/** 图片滚动回调 */
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didScrollToIndex:(NSInteger)index {
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.allProductList.count;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    JSLProductCell *cell = [JSLProductCell cellWithTableView:tableView];
    [cell configProductCellContent:self.allProductList[indexPath.row]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *info = self.allProductList[indexPath.row];

    JSLLoanDetialController *loanDetial = [[JSLLoanDetialController alloc] init];
    [loanDetial configLoanDetial:info fromFlag:LoanFromNormal];
    [self pushViewController:loanDetial animated:YES];
    
    
    
}

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    return 109.0;
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - action
-(void)kindClickAction:(UIButton *)sender {
    
    JSLLabelLoanController *vc = [[JSLLabelLoanController alloc] init];
    vc.productType = [NSString stringWithFormat:@"%ld",(sender.tag -1000 +1)];
    [self pushViewController:vc animated:YES];
}
#pragma mark - get mothe
- (UIView *)kindBackView {
    if (_kindBackView == nil) {
        _kindBackView = [[UIView alloc] init];
        _kindBackView.frame = CGRectMake(0, CGRectGetMaxY(self.canScrollerView.frame)+10*AutoSizeScaleYY, SCREEN_WIDTH, 42*AutoSizeScaleYY);
        
        NSArray *imageArray = @[@"phone-loan",@"zhima-loan",@"big-loan"];
        CGFloat width = (CGRectGetWidth(self.view.frame) - 40.0*AutoSizeScaleXX)/3.0;
        for (NSInteger i = 0; i <imageArray.count; i++) {
            UIButton *button = [JSLKitFactory jsl_imageButtonWithFrame:CGRectMake(10*AutoSizeScaleXX +(10*AutoSizeScaleXX +width)*i, 0, width, 42*AutoSizeScaleYY) superView:_kindBackView setImage:nil setBackImage:imageArray[i] target:self action:@selector(kindClickAction:)];
            button.tag = i +1000;
            
        }
    }
    
    return _kindBackView;
}
- (SYJMoreProductView *)canScrollerView {
    if (_canScrollerView == nil) {
        _canScrollerView = [[SYJMoreProductView alloc] init];
        _canScrollerView.moreProductViewDelegate = self;
        
        _canScrollerView.frame = CGRectMake(0, CGRectGetMaxY(self.ccpView.frame), SCREEN_WIDTH, 82*AutoSizeScaleYY);
    }
    return _canScrollerView;
}
- (UIView *)headerView {
    if (_headerView == nil) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, 348)];
    }
    
    return _headerView;
}
- (SDCycleScrollView *)cycleScrollerView {
    if (_cycleScrollerView == nil) {
        
        _cycleScrollerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.width, self.view.width *188.0/375.0) delegate:self placeholderImage:[UIImage imageNamed:@"Banner-place"]];
        _cycleScrollerView.autoScrollTimeInterval = 3.0;// 自动滚动时间间隔
        //        _cycleScrollerView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;// 翻页 右下角
        _cycleScrollerView.titleLabelBackgroundColor = [UIColor clearColor];// 图片对应的标题的 背景色。（因为没有设标题）
    }
    
    return _cycleScrollerView;
}

- (CCPScrollView *)ccpView {
    if (_ccpView ==nil) {
        UIImageView *imageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"index_icon_notice"]];
        
        imageV.frame = CGRectMake(15*AutoSizeScaleXX, CGRectGetMaxY(self.cycleScrollerView.frame)+10 , 12, 11);
        [self.headerView addSubview:imageV];
        _ccpView = [[CCPScrollView alloc] initWithFrame:CGRectMake(34*AutoSizeScaleXX, CGRectGetMaxY(self.cycleScrollerView.frame), SCREEN_WIDTH - 34*AutoSizeScaleXX-15*AutoSizeScaleXX, 30.0)];
        
        _ccpView.backGroundColor = [UIColor redColor];
        
        _ccpView.titleArray = [NSArray arrayWithObjects:@"iPhone6s上线32G内存手机你怎么看？",@"亲爱的朋友们2016年还有100天就要过去了,2017年您准备好了吗?",@"今年双11您预算了几个月的工资？",@"高德与百度互掐，你更看好哪方？", nil];
        
        _ccpView.titleFont = 10;
        
        _ccpView.titleColor = [@"#8f8f8f" hexStringToColor];
        
        MJWeakSelf;
        [_ccpView clickTitleLabel:^(NSInteger index,NSString *titleString) {
            NSDictionary *info = self.noticeList[index];
           
            if ([UserManager checkLogin:weakSelf]) {
                
                if ([JSLKitFactory isNotNull:info[@"productId"]]) {
                    JSLLoanDetialController *loanDetial = [[JSLLoanDetialController alloc] init];
                    [loanDetial configLoanDetial:info fromFlag:LoanFromNormal];
                    [weakSelf pushViewController:loanDetial animated:YES];
                }
                
            }
        }];
        
        
        
        
        
    }
    
    return _ccpView;
}

#pragma mark - get
- (UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-49) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        _tableView.scrollEnabled = YES;
        _tableView.rowHeight = 100 *AutoSizeScaleYY +10*AutoSizeScaleYY;
        _tableView.backgroundColor = BACKGROUND_COLOR;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:_tableView];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
        
        
    }
    
    return _tableView;
}

- (NSArray *)bannerList{
    if (_bannerList == nil) {
        _bannerList = [[NSArray alloc] init];
    }
    return _bannerList;
}
- (NSArray *)hotList {
    if (_hotList == nil) {
        _hotList = [[NSArray alloc] init];
    }
    return _hotList;
}
- (NSArray *)allProductList {
    if (_allProductList == nil) {
        _allProductList = [[NSArray alloc] init];
    }
    return _allProductList;
}

- (NSArray *)noticeList {
    if (_noticeList == nil) {
        _noticeList = [[NSArray alloc] init];
        
    }
    return _noticeList;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleLightContent;
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
